let router = require('express').Router()
let db = require('../db')

// 列表
router.get('/cate', async (req, res, next) => {
    let data = await db({
        sql: 'select * from en_article_cate',
        next
    })
    res.success('', {
        rows: data
    })
})

// 新增
router.post('/cate', async (req, res, next) => {
    let body = req.body
    let list = await db({
        sql: 'select name from en_article_cate',
        next
    })
    if (list.map(item => item.name).includes(body.name)) return res.fail('类别名称已被占用')
    console.log(body)
    await db({
        sql: 'insert into en_article_cate set ?',
        value: body,
        next
    })
    res.success('新增成功！')
})

// 编辑
router.put('/cate', async (req, res, next) => {
    await db({
        sql: 'update en_article_cate set ? where id = ?',
        value: [req.body, req.body.id]
    })
    res.success('操作成功！')
})

// 删除
router.delete('/cate/:id', async (req, res, next) => {
    await db({
        sql: 'delete from en_article_cate where id = ?',
        value: req.params.id
    })
    res.success('操作成功！')
})

// 按类别查数量
router.get('/cate_group', async (req, res, next) => {
    let data = await db({
        sql: 'select en_article_cate.*, count(*) as total from en_article_info INNER join en_article_cate on en_article_info.cate_id = en_article_cate.id GROUP BY en_article_cate.id;',
        next
    })
    res.success('', data)
})

module.exports = router